package xyz.xtt.exchange.plus;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Invocation;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyAfterInterceptor implements Interceptor {

	@Override
	public Object intercept(Invocation invocation) throws Throwable {
//		MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
//		Object parameter = invocation.getArgs()[1];
//
//		Configuration configuration = mappedStatement.getConfiguration();
//		Object target = invocation.getTarget();
//		StatementHandler handler = configuration.newStatementHandler((Executor) target, mappedStatement, parameter, RowBounds.DEFAULT, null, null);
//		// 记录SQL
//		BoundSql boundSql = handler.getBoundSql();
//		// 记录耗时
//		long start = System.currentTimeMillis();
//		// 执行真正的方法
//		Object result = invocation.proceed();
//		long end = System.currentTimeMillis();
//		// 记录影响行数
//		int affectedRows = Integer.valueOf(Integer.parseInt(result.toString()));
//		// 记录时间
//		log.info("executed times: {}, sql: {}, affected rows: {}, time cost: {} ms", new Date(), boundSql.getSql(), affectedRows, end - start);
//		return result;
		long startTime = System.currentTimeMillis();
		Object result = invocation.proceed();
		long endTime = System.currentTimeMillis();
		long duration = endTime - startTime;

		StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
		String sql = statementHandler.getBoundSql().getSql();
		System.out.println("SQL: " + sql);
		System.out.println("Execution time: " + duration + " ms");

		return result;
	}

}
